package me.zhanshi123.pixelpaygui.gui.open

import me.zhanshi123.pixelpaygui.gui.paykit.PayKitGui
import org.bukkit.ChatColor
import org.bukkit.Material
import org.bukkit.entity.Player
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.inventory.InventoryClickEvent

class OpenGuiListener : Listener {
    @EventHandler
    fun onClick(e: InventoryClickEvent) {
        val inventory = e.clickedInventory ?: return
        val player = e.whoClicked as Player
        if (player.openInventory.topInventory.holder !is OpenGuiHolder) {
            return
        }
        e.isCancelled = true
        if (inventory.holder !is OpenGuiHolder) {
            return
        }
        val holder = inventory.holder as OpenGuiHolder
        if (holder.kit != null) {
            return
        }
        val slot = e.slot
        if (slot == OpenGui.nextSlot) {
            OpenGui.setInventory(inventory, holder.page + 1)
            return
        }
        if (slot == OpenGui.previousSlot && holder.page != 1) {
            OpenGui.setInventory(inventory, holder.page - 1)
            return
        }
        if (e.currentItem.type != Material.PAPER) {
            return
        }
        val kitName = ChatColor.stripColor(e.currentItem.itemMeta.displayName)
        e.whoClicked.openInventory(PayKitGui.getInventory(kitName, inventory))
    }
}